<template>
  <!-- Appointment 页面 -->
  <div class="appoint_ment">
    <!-- 替换原来的 appoint_ment_count 部分  card 头部  -->
    <AppointmentCard
      :items="cardItems"
      :initialQuantity="quantity"
      @quantity-change="handleQuantityUpdate"
    />

    <!-- Coupon/Discount +Total order price  + 优惠劵弹窗 此处展示 -->
    <AppointmentCouponDiscount
      ref="couponDiscountRef"
      :baseprice="totalPrice"
      @updatetotalPrice="handletotalPrice"
      @couponApplied="handleCouponApplied"
    />

    <!-- Payment method -->
    <div class="appoint_ment_payment">
      <div class="appoint_ment_payment_title">
        <p>Payment method</p>
      </div>
      <!-- 单选框 -->
      <van-radio-group v-model="paymentMethod">
        <van-radio
          v-for="(item, index) in paymentOptions"
          :key="index"
          :name="item.value"
          icon-size="16px"
          checked-color="#18b792"
          >{{ item.label }}</van-radio
        >
      </van-radio-group>
    </div>
    <!-- Booking instructions -->
    <div class="appoint_ment_instructions">
      <div class="appoint_ment_instructions_title">
        <p>Booking instructions</p>
      </div>
      <div class="appoint_ment_instructions_text">
        <p>
          {{ bookingInstructions }}
        </p>
      </div>
    </div>
    <!-- Booking button -->
    <div class="appoint_ment_button">
      <div
        class="appoint_ment_button_title"
        :value="date"
        @click="showCalendar = true"
      >
        <img :src="appointmentIcon" alt="" />
        <p>{{ timeTitle }}</p>
      </div>
      <div class="appoint_ment_button_btn appoint_ment_flex">
        <div class="btn_l">
          <p>
            Total <span class="pricecolor">C${{ receivedPrice }}</span>
          </p>
        </div>
        <van-button
          :loading="loading"
          @click="validateForm"
          round
          color="#1ab692"
          >Submit & Book</van-button
        >
      </div>
    </div>

    <!-- 日期选择弹窗 -->
    <van-calendar
      confirm-text="Submit"
      @close="handleCalendarClose"
      :show-mark="false"
      color="#1ab692"
      title="Schedule"
      v-model:show="showCalendar"
      :default-date="defaultDate"
      :min-date="minDate"
      :max-date="maxDate"
      :allow-same-day="true"
      @select="selectFn"
      switch-mode="range"
    >
      <!-- 自定义日历副标题 -->
      <template #subtitle>October {{ currentYear }}</template>
      <!-- 自定义底部内容给 -->
      <template #footer>
        <div class="footer_title">
          <p>Available time</p>
        </div>
        <div class="footer_timer">
          <div
            v-for="item in footer_timerData"
            :key="item.id"
            class="timer_item"
            :class="{
              selected: item.selected,
              disabled: item.disabled,
            }"
            @click="handleItemClick(item.id)"
          >
            {{ item.timer }}
          </div>
        </div>
        <van-button
          size="large"
          round
          color="#1ab692"
          :loading="loading"
          @click="handleCalendarSubmit"
          >Submit</van-button
        >
      </template>
    </van-calendar>
  </div>
</template>

<script setup>
/************************导入部分************************************/
import { ref, computed, watch, nextTick } from "vue";
import { showToast } from "vant";
import { useRouter } from "vue-router";
import { Locale } from "vant";
import enUS from "vant/es/locale/lang/en-US";
import AppointmentCard from "@/view/AppointmentCard.vue";
import AppointmentCouponDiscount from "@/view/AppointmentCouponDiscount.vue";

/************************常量定义************************************/
const SERVICE_PRICES = {
  CAT_THERAPY: 280,
  RABIES_VACCINE: 78,
};

const paymentOptions = [
  { value: "1", label: "Online payment" },
  { value: "2", label: "PayPal" },
  { value: "3", label: "Stripe" },
];

const bookingInstructions = `
  Please make an appointment 2 hours in advance. Refund rules: Return at
  any time, expired refund. In order to protect the healthy growth of
  minors, minor users should obtain the consent of their guardians before
  purchasing and experiencing them. Please do not buy products that are
  not suitable for their age.
`;

const appointmentIcon = new URL("../assets/Make.png", import.meta.url).href;

/************************响应式状态************************************/
const router = useRouter();
const date = ref(new Date());
const quantity = ref(1);
const paymentMethod = ref(null);
const showCalendar = ref(false);
const loading = ref(false);
const timeTitle = ref("Make an appointment");
const couponDiscountRef = ref(null);

const currentDate = new Date();
const minDate = ref(new Date());
const maxDate = ref(new Date());
const defaultDate = ref([
  new Date(),
  new Date(currentDate.setDate(currentDate.getDate() + 18)),
]);

const footer_timerData = ref([
  { id: 1, timer: "09:00 am", selected: false, disabled: false },
  { id: 2, timer: "10:00 am", selected: false, disabled: false },
  { id: 3, timer: "12:00 am", selected: false, disabled: true },
  { id: 4, timer: "14:00 am", selected: false, disabled: true },
  { id: 5, timer: "16:00 am", selected: false, disabled: false },
  { id: 6, timer: "17:00 am", selected: false, disabled: true },
  { id: 7, timer: "18:00 am", selected: false, disabled: false },
  { id: 8, timer: "20:00 am", selected: false, disabled: false },
]);

/************************计算属性************************************/
const totalPrice = computed(() => {
  return (
    (SERVICE_PRICES.CAT_THERAPY + SERVICE_PRICES.RABIES_VACCINE) *
    quantity.value
  );
});

// 修复：将receivedPrice的初始化移到totalPrice之后
const receivedPrice = ref(totalPrice.value);

const cardItems = computed(() => [
  {
    text: "3 Doses of cat therapy",
    price: `C$${SERVICE_PRICES.CAT_THERAPY}`,
  },
  {
    text: "1 dose of rabies vaccine",
    price: `C$${SERVICE_PRICES.RABIES_VACCINE}`,
  },
  {
    text: "Qty",
    isStepper: true,
  },
  {
    text: "Total",
    price: `C$${totalPrice.value}`,
    isSpecial: true,
  },
]);

const currentYear = computed(() => new Date().getFullYear());

/************************工具函数************************************/
const formatDate = (date) => {
  const d = new Date(date);
  const day = String(d.getDate()).padStart(2, "0");
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const year = d.getFullYear();
  return `${day}/${month}/${year}`;
};

const formatTime = (timeStr) => {
  const [time, period] = timeStr.split(" ");
  let [hours, minutes] = time.split(":");

  if (period === "pm" && hours !== "12") {
    hours = String(Number(hours) + 12);
  } else if (period === "am" && hours === "12") {
    hours = "00";
  }

  return `${hours}:${minutes}:00`;
};

// 修改MyShowToastShowDialog函数使其返回Promise
const MyShowToastShowDialog = (type, options = {}) => {
  return new Promise((resolve) => {
    const {
      message = "",
      position = "top",
      duration = 1500,
      className = "custom-toast-error ",
    } = options;

    if (type === "toast") {
      showToast({
        message,
        position,
        duration,
        className,
        onClose: resolve, // toast关闭时resolve
      });
    }
  });
};

/************************事件处理************************************/
const selectFn = (value) => {
  date.value = new Date(value);
};

const handleQuantityUpdate = (newQuantity) => {
  quantity.value = newQuantity;
};

const handleItemClick = (id) => {
  footer_timerData.value = footer_timerData.value.map((item) => {
    if (item.id === id) {
      if (!item.disabled) {
        return { ...item, selected: !item.selected };
      }
    }
    return { ...item, selected: false };
  });
};

const handletotalPrice = (newPrice) => {
  receivedPrice.value = newPrice;
};

const couponInfoCode = ref(null);
// 统一处理优惠信息（手动或自动）
const handleCouponApplied = (couponInfo, isManualSubmit) => {
  if (!couponInfo) return;
  // 无论优惠是默认选择还是手动添加，都会更新 couponInfoCode
  couponInfoCode.value = couponInfo.code; // 自动赋值的关键！
  if (couponInfo.addCode) {
    MyShowToastShowDialog("toast", {
      message: "折扣添加成功！",
      className: "custom-toast",
    });
  } else if (couponInfo.code && isManualSubmit) {
    MyShowToastShowDialog("toast", {
      message: "申请优惠成功!",
      className: "custom-toast",
    });
  }
};
// 定义一个标志变量，用于判断是否是用户手动提交
const hasSelectedTime = ref(false); // 新增状态变量用于标记用户是否通过正常流程选择了时间
const handleCalendarSubmit = async () => {
  const selectedTime = footer_timerData.value?.find((item) => item.selected);
  if (!selectedTime) {
    MyShowToastShowDialog("toast", {
      message: "请选择预约时间",
    });
    return;
  }

  loading.value = true;

  try {
    await new Promise((resolve) => setTimeout(resolve, 2000));
    const formattedTime = formatTime(selectedTime.timer);
    const formattedDate = formatDate(date.value);
    timeTitle.value = `${formattedTime} ${formattedDate}`;
    showCalendar.value = false;
    hasSelectedTime.value = true;
    MyShowToastShowDialog("toast", {
      message: `预约成功！时间：${formattedTime} ${formattedDate}`,
      className: "custom-toast",
    });
  } finally {
    loading.value = false;
  }
};
// 新增关闭事件处理
const handleCalendarClose = () => {
  if (!hasSelectedTime.value) {
    footer_timerData.value.forEach((item) => (item.selected = false)); // 清除已选时间
  }
};

const validateForm = async () => {
  try {
    if (quantity.value < 1) {
      MyShowToastShowDialog("toast", {
        message: "采购数量必须大于1",
      });
      return;
    }

    if (!paymentMethod.value) {
      await MyShowToastShowDialog("toast", {
        message: "请选择付款方式",
      });
      return;
    }

    // 新增时间选择校验
    const selectedTime = footer_timerData.value.find((item) => item.selected);//获取选中的时间
    if (!selectedTime || !hasSelectedTime.value) {
      showCalendar.value = true;
      await MyShowToastShowDialog("toast", { message: "请选择预约时间" });
      return;
    }
    //开始加载
    loading.value = true;
    // 确保UI有机会更新
    await nextTick();
    try {
      // 模拟API调用延迟
      await new Promise((resolve) => setTimeout(resolve, 2000));

      // 提交逻辑
      await submitBooking();
    } finally {
      // 确保无论如何都会关闭loading
      loading.value = false;
    }

    await submitBooking();
  } catch (error) {
    console.error("Validation error:", error);
    showToast({
      message: "An error occurred, please try again",
      position: "top",
    });
  }
};

const submitBooking = async () => {
  try {
    MyShowToastShowDialog("toast", {
      message: "预订已成功提交!",
      className: "custom-toast",
    });

    const appointmentData = {
      date: date.value || formatDate(new Date()),
      price: receivedPrice.value,
      paymentMethod: paymentOptions.find(
        (item) => item.value === paymentMethod.value
      )?.label,
      couponInfoCode: couponInfoCode.value,
    };

    router.push({
      name: "AppointmentSuccess",
      query: {
        data: JSON.stringify(appointmentData),
      },
    });
  } catch (error) {
    console.error("Submission error:", error);
    throw error;
  }
};

/************************初始化设置************************************/
Locale.use("en-US", enUS);

maxDate.value = new Date(
  currentDate.getFullYear(),
  currentDate.getMonth(),
  currentDate.getDate()
);

watch(
  totalPrice,
  (newVal) => {
    nextTick(() => {
      couponDiscountRef.value?.initBestDiscount();
    });
  },
  { immediate: true }
);
</script>


<style lang="less">
.appoint_ment {
  padding: 10px;
  padding-top: 48px;
  font-size: 14px;
  padding-bottom: 180px;

  // 定义公共样式混合
  .card-style(@margin-top: 10px) {
    background-color: #fff;
    border-radius: 10px;
    padding: 0 10px;
    margin-top: @margin-top;
  }

  // 公共flex属性
  .appoint_ment_flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  img {
    width: 20px;
    margin-right: 5px;
    vertical-align: bottom;
  }

  .pricecolor {
    color: #ef7727;
    font-weight: bold;
  }

  // 支付方式部分样式
  .appoint_ment_payment {
    background-color: #fff;
    border-radius: 10px;
    padding: 0 10px;
    margin-top: 10px;
    padding: 10px;

    .van-radio-group {
      .van-radio {
        height: 45px;
        background-color: #f2f4f5;
        border-radius: 5px;
        margin-top: 10px;
        padding: 0 10px;

        .van-radio__icon {
          border: 1.4px solid #c8c9cc;
          border-radius: 50%;
          background-color: #fff;
        }
      }
    }
  }

  // 指示说明部分样式
  .appoint_ment_instructions {
    .card-style();
    font-size: 14px;
    color: #626467;
    padding: 10px;

    .appoint_ment_instructions_text {
      word-wrap: break-word;
      overflow-wrap: break-word;
      white-space: normal;
    }
  }

  // 底部按钮部分样式
  .appoint_ment_button {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 120px;
    background-color: #fff;
    padding: 0 10px;
    box-sizing: border-box;

    .appoint_ment_button_title {
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 15px;
      color: #1ab692;
    }

    .appoint_ment_button_btn {
      height: 30px;
      font-size: 15px;
      margin-top: 10px;

      .van-button {
        width: 160px;
        font-size: 16px;
        font-weight: bold;
      }
    }
  }
}

// 禁用选项样式 优惠卷过期
.disabled-item {
  opacity: 0.6;
  pointer-events: none;
  .van-radio__icon {
    background-color: #f2f4f5;
  }
}
/* 自定义 Toast 样式 成功 */
.custom-toast {
  background-color: #1ab692;
  color: white;
  border-radius: 8px;
  padding: 15px 20px;
  text-align: center;
  line-height: 1.5;
  white-space: nowrap;
}
/* 错误提示样式 */
.custom-toast-error {
  background: rgba(255, 59, 48, 0.9);
  color: white;
  border-radius: 8px;
  padding: 12px 20px;
  z-index: 9999;
}

// 日期选择弹窗样式
.van-calendar {
  .van-calendar__header {
    box-shadow: none;

    .van-calendar__header-subtitle {
      padding: 0 12px;
      .van-calendar__header-subtitle-text {
        color: #5e5e5e;
        font-size: 15px;
      }
      .van-calendar__header-action {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background-color: #e6e6e9;
        & > i::before {
          font-weight: bold;
          font-size: 18px;
          color: #555b62;
        }
      }
    }
  }
  .van-calendar__body {
    max-height: 210px;
    .van-calendar__month {
      .van-calendar__days {
        .van-calendar__day {
          height: 38px;
          margin-left: 0 !important;
        }
      }
    }
  }
  // 选中的日期
  .van-calendar__selected-day {
    border-radius: 50%;
    width: 38px;
    height: 38px;
  }
  .van-calendar__footer {
    padding-bottom: env(safe-area-inset-bottom); /* 适配全面屏 */
    padding: 0 10px;
    .footer_title {
      font-size: 16px;
      font-weight: bold;
    }
    .footer_timer {
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-wrap: wrap;
      .timer_item {
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 12px;
        color: #000;
        padding: 6px 14px;
        border-radius: 20px;
        margin-top: 8px;
        box-sizing: border-box;
        background-color: #e5e7eb;
        &.selected {
          background-color: #c8f5ec; /* 选中时绿色 */
          border: 1.5px solid #3cbca0; /* 选中时绿色 */
          color: #2cb692;
        }
        &.disabled {
          opacity: 0.3;
          pointer-events: none;
        }
      }
    }
    .van-button {
      position: fixed;
      width: 90%;
      left: 50%;
      bottom: 25px;
      transform: translateX(-50%);
      height: 40px;
    }
  }
  .van-calendar__weekdays {
    font-size: 12px;
    padding: 0 10px;
    .van-calendar__weekday {
      &::after {
        content: ".";
        display: inline;
      }
    }
  }
}
</style>